package com.uy.cuantoconocesdeuruguay.utiles;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.uy.cuantoconocesdeuruguay.MainActivity;
import com.uy.cuantoconocesdeuruguay.controllers.GoogleAnalyticsTracker;
import com.uy.cuantoconocesdeuruguay.datatypes.FacebookUser;
import com.uy.cuantoconocesdeuruguay.dialogs.ErrorOccurredDialogUtils;
import com.uy.cuantoconocesdeuruguay.exceptions.ConnectivityException;
import com.uy.cuantoconocesdeuruguay.server.ServerConnector;

@SuppressLint("NewApi")
public class FacebookHelper {	
	
	private static HashMap<String,FacebookUser> friendsList;
	private static final Object mutex = new Object();
	
	public static HashMap<String,FacebookUser> getAllFriends(final Activity activity) { 
        Session activeSession = Session.getActiveSession();
        if (activeSession == null){
        	Intent i = new Intent(activity.getApplicationContext(), MainActivity.class);
        	activity.startActivity(i);
        	activity.finish();
        	return null;
        }
        if (activeSession.getState().isOpened()){
        	final HashMap<String,FacebookUser> returningList = new HashMap<String,FacebookUser>();
            Bundle params = new Bundle();
            params.putString("fields", "id, name, first_name, last_name, picture");
        	final Request friendRequest = new Request(
    		    activeSession,
    		    "/me/friends",
    		    params,
    		    HttpMethod.GET,
    		    new Request.Callback() {
    		        public void onCompleted(Response response) {
    		        	GraphObject graphObject = response.getGraphObject();
    		        	if (graphObject != null) {
    	                    JSONObject jsonObject = graphObject.getInnerJSONObject();
    	                    try {
    	                    	String DATA = "data";
    	                    	String FIRST_NAME = "first_name";
    	                    	String ID = "id";
    	                    	String PICTURE = "picture";
    	                    	String URL = "url";
    	                    	String LAST_NAME = "last_name";
    	                    	String NAME = "name";    	                    	
    	                    	JSONArray array = jsonObject.getJSONArray(DATA);
    	                    	for (int i = 0; i < array.length(); ++i) {
    	                    		FacebookUser user = new FacebookUser();
    	                    		try{
	    	                    		JSONObject object = (JSONObject) array.get(i);
	    	                    		user.setFirst_name((String) object.get(FIRST_NAME));
	    	                    		user.setId((String) object.get(ID));
		    	                    		JSONObject pictureJSON = (JSONObject) object.get(PICTURE);
		    	                    		JSONObject pictureData = pictureJSON.getJSONObject(DATA);
		    	                    		user.setPicture((String) pictureData.get(URL));
	    	                    		user.setLast_name((String) object.get(LAST_NAME));
	    	                    		user.setName((String) object.get(NAME));
    	                    		}catch (Exception e){
    	            					GoogleAnalyticsTracker.trackException(activity, e);
    	                    			e.printStackTrace();
    	                    		}finally{
    	                    			returningList.put(user.getId(),user);
    	                    		}
    	                    	}
    	                    } catch (JSONException e) {
    	    					GoogleAnalyticsTracker.trackException(activity, e);
    	                    	e.printStackTrace();
	    	                }
	    	            }
    		        }
    		    }
    		);
        	if (friendsList != null){
        		AsyncTask< Void, Void, Void> friendFetcher = new AsyncTask<Void, Void, Void>(){
        			@Override
        			protected Void doInBackground(Void... params) {
        				friendRequest.executeAndWait();
        				synchronized (mutex) {
        					friendsList = returningList;
        				} 
        				return null;
        			}
        		};
        		if (android.os.Build.VERSION.SDK_INT > 10) {
        			friendFetcher.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        		}else{
        			friendFetcher.execute();
        		}
        		return friendsList;
        	}else{
				friendRequest.executeAndWait();
				friendsList = returningList;
        	}
            return returningList;
        }
        return null;
    }
	
	public static void onUserInfoFetched(GraphUser user, final Activity activity){
		if (user != null) {
        	Session session = Session.getActiveSession();
        	Request r = new Request(
        		session,
    		    "/me",
    		    null,
    		    HttpMethod.GET,
    		    new Request.Callback() {
        			public void onCompleted(Response response) {
    		        	GraphObject graphObject = response.getGraphObject();
    		        	if (graphObject != null) {
    	                    JSONObject jsonObject = graphObject.getInnerJSONObject();
    	                    try {
    	                    	try{
    	                    		ServerConnector.facebookLogin((String) jsonObject.get("id"));
    	                    	}catch (ConnectivityException e){
    	        					ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(activity, e);
    	        					dialog.createErrorOccurredPopup();
    	                    		e.printStackTrace();
    	                    		return;
    	                    	}
                            	MainActivity.userData.setFacebookid((String) jsonObject.get("id"));
                            	MainActivity.userData.setFacebookName((String) jsonObject.get("first_name") + StringPool.SPACE + (String) jsonObject.get("last_name"));
                            	//GET PICTURE URL
                            	JSONObject pictureJSON = (JSONObject) jsonObject.get("picture");
	                    		JSONObject pictureData = pictureJSON.getJSONObject("data");
                            	MainActivity.userData.setFacebookImage((String) pictureData.get("url"));
                        		MainActivity.userData.setFacebookLoaded(true);
    	                    } catch (JSONException e) {
    	    					GoogleAnalyticsTracker.trackException(activity, e);
    	                    	e.printStackTrace();
	    	                }
	    	            }
    		        }
        		}
        	);
            Bundle params = new Bundle();
            params.putString("fields", "id, name, first_name, last_name, picture");
            r.setParameters(params);
            if (ConnectionManager.isNetworkConnected(activity)){
            	r.executeAsync();        
            }else{
				ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(activity, null);
				dialog.createErrorOccurredPopup();
            }
        }
	}
	
	public static void printFacebookHash(Activity activity){
		PackageInfo info;
		try {
			info = activity.getPackageManager().getPackageInfo("com.uy.cuantoconocesdeuruguay", PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md;
				md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());		        
				String something = new String(android.util.Base64.encode(md.digest(), 0));
				Log.e("hash key", something);
			}
		} catch (NameNotFoundException e) {
			GoogleAnalyticsTracker.trackException(activity, e);
			Log.e("name not found", e.toString());
		} catch (NoSuchAlgorithmException e) {
			GoogleAnalyticsTracker.trackException(activity, e);
			Log.e("no such an algorithm", e.toString());
		} catch (Exception e) {
			GoogleAnalyticsTracker.trackException(activity, e);
			Log.e("exception", e.toString());
		}
	}
}
